package com.qny.ai.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final String DEFAULT_SECRET = "change-this-demo-secret-key-please-32-bytes-min";
    private static final long DEFAULT_EXPIRE_MS = 1000L * 60 * 60 * 24 * 7; // 7 days

    private static SecretKey buildKey(String secret) {
        byte[] keyBytes = (secret == null || secret.isEmpty() ? DEFAULT_SECRET : secret).getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    public static String generateToken(String subject, Map<String, Object> claims, String secret, Long expireMs) {
        long now = System.currentTimeMillis();
        long exp = now + (expireMs == null ? DEFAULT_EXPIRE_MS : expireMs);
        return Jwts.builder()
                .setSubject(subject)
                .addClaims(claims)
                .setIssuedAt(new Date(now))
                .setExpiration(new Date(exp))
                .signWith(buildKey(secret), SignatureAlgorithm.HS256)
                .compact();
    }

    public static Claims parseToken(String token, String secret) {
        return Jwts.parserBuilder()
                .setSigningKey(buildKey(secret))
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}


